<template>
  <div class="chat-container">
    <!-- 欢迎组件 -->
    <Welcome />
    <!-- 会话管理组件 -->
    <Conversations />
    <!-- 气泡消息列表组件 -->
    <BubbleList :list="messages" />
    <!-- 智能输入框组件 -->
    <Sender v-model="isSending" @send="sendMessage" @stop="stopGenerating">
      <template #prefix>
        <div class="model-select">
          <!-- 这里由于 Element-Plus-X 未明确有类似 t-tooltip 和 t-select 的组件，可使用 ElementPlus 原生组件替代 -->
          <el-tooltip content="切换模型" trigger="hover">
            <el-select v-model="selectValue" :options="selectOptions" value-key="value">
              <el-option v-for="option in selectOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
            </el-select>
          </el-tooltip>
          <el-button class="check-box" :class="{ 'is-active': isChecked }" type="text" @click="checkClick">
          </el-button>
        </div>
      </template>
    </Sender>
    <!-- 思考中组件 -->
    <Thinking v-if="isThinking" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import {
  BubbleList,
  Sender,
  Thinking,
  Welcome,
  Conversations
} from 'vue-element-plus-x';
import { ElTooltip, ElSelect, ElOption, ElButton } from 'element-plus';
import { SystemSumIcon } from 'tdesign-icons-vue-next';
import { CheckCircleIcon } from 'tdesign-icons-vue-next';

// 初始化数据
const messages = ref([
  {
    role: 'system',
    content: '👋 欢迎使用AI超级智能体！我可以帮你完成各种任务，包括网络搜索、文件操作、数据处理等。请告诉我你的需求。',
    datetime: new Date().toLocaleString(),
    isLoading: false,
    reasoning: '',
    reasoningExpanded: false,
    isReasoningLoading: false
  }
]);
const isSending = ref();
const currentStream = ref(null);
const userAvatar = 'https://example.com/user-avatar.png';
const aiAvatar = 'https://example.com/ai-avatar.png';
const isThinking = ref(false);



const selectOptions = [
  {
    label: '默认模型',
    value: 'default',
  },
  {
    label: 'deepseek-r1',
    value: 'deepseek-v2',
  },
  {
    label: '混元',
    value: 'hunyuan',
  },
];
const selectValue = ref('default');
const isChecked = ref(false);

const checkClick = () => {
  isChecked.value = !isChecked.value;
};

const handleChange = (value, { index }) => {
  console.log('handleChange', value, index);
};

// 发送消息
const sendMessage = (value) => {
  if (!value.trim() || isSending.value) return;

  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: value,
    datetime: new Date().toLocaleString(),
    isLoading: false,
    reasoning: '',
    reasoningExpanded: false,
    isReasoningLoading: false
  };
  messages.value.push(userMessage);

  // 清空输入框并设置发送状态
  isSending.value = true;
  isThinking.value = true;

  // 建立SSE连接
  const eventSource = new EventSource(`/api/ai/manus/chat?message=${encodeURIComponent(value)}`);
  currentStream.value = eventSource;

  // 监听SSE消息
  eventSource.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log('SSE消息:', data)
      // 创建新的AI回复消息
      const newMessage = {
        role: 'ai',
        content: data.content || '',
        datetime: new Date().toLocaleString(),
        isLoading: !(data.content || ''), // 如果没有content，标记为加载中
        reasoning: data.reaContent || '',
        reasoningExpanded: false,
        isReasoningLoading: !(data.reaContent || '') // 如果没有reaContent，标记思考过程为加载中
      };

      // 添加新消息到列表
      messages.value.push(newMessage);

      // 确保消息列表更新
      messages.value = [...messages.value];
      isThinking.value = false;
    } catch (error) {
      console.error('解析SSE消息失败:', error);
      // 显示错误消息
      const errorMessage = {
        role: 'error',
        content: '抱歉，解析响应时出错，请重试。',
        datetime: new Date().toLocaleString(),
        isLoading: false,
        reasoning: '',
        reasoningExpanded: false,
        isReasoningLoading: false
      };
      messages.value.push(errorMessage);
      isThinking.value = false;
    }
  };

  // 监听SSE完成
  eventSource.onend = () => {
    isSending.value = false;
    currentStream.value = null;
    eventSource.close();
  };

};

// 停止生成
const stopGenerating = () => {
  if (currentStream.value) {
    currentStream.value.close();
    isSending.value = false;
    currentStream.value = null;
  }
};

// 清除历史记录
const clearHistory = () => {
  messages.value = [
    {
      role: 'system',
      content: '👋 欢迎使用AI超级智能体！我可以帮你完成各种任务，包括网络搜索、文件操作、数据处理等。请告诉我你的需求。',
      datetime: new Date().toLocaleString(),
      isLoading: false,
      reasoning: '',
      reasoningExpanded: false,
      isReasoningLoading: false
    }
  ];
};

// 处理滚动事件
const handleScroll = () => {
  // 可根据需求添加滚动处理逻辑
};
</script>

<style scoped>
.chat-container {
  width: 700px;
  margin: 0 auto;
  padding: 20px;
}

.reasoning-content {
  white-space: pre-wrap;
  font-size: 14px;
  color: #666;
  padding: 10px;
}
</style>